package com.lyy;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Set;

/**
 * @author Liangyaoyun
 */
public class JedisClusterUtil {
    /*
    *
    * 超时时间
    * */
    private static final int TIMEOUT=10000;

    /*
    * 集群模式:Jedis集群链接池
    * */
    private static final JedisCluster jedisCluster;

    /*
    * 集群模式:全部集群节点端号，逗号分隔
    *
    * */
    private static final Set<HostAndPort>CLUSTER_NODES=Set.of(
            new HostAndPort("192.168.159.77",7004),
            new HostAndPort("192.168.159.77",7005),
            new HostAndPort("192.168.159.77",7006),
            new HostAndPort("192.168.159.77",7007),
            new HostAndPort("192.168.159.77",7008),
            new HostAndPort("192.168.159.77",7009)
    );

    static {
        //初始化Jedis链接池配置实例:最大链接,最大阻塞时间,最大空闲,最小空间
        JedisPoolConfig poolConfig=new JedisPoolConfig();
        poolConfig.setMaxIdle(8);
        poolConfig.setMinIdle(0);
        poolConfig.setMaxTotal(8);
        poolConfig.setMaxWaitMillis(10000);
        //初始化Jedis集群链接池实例
        jedisCluster=new JedisCluster(CLUSTER_NODES,TIMEOUT,poolConfig);

    }

    /**
     * 从Jedis集群链接池中获取并返回一个对应端号的Jedis链接
     *  @Param hostAndPort 集群节点,格式为:IP：PORT
     *  @return 按指定的集群节点返回对应该集群节点的Jedis链接
     */
    public static Jedis getJedi(String hostAndPort){
        return jedisCluster.getClusterNodes().get(hostAndPort).getResource();
    }
}
